import React, { useState, useEffect } from 'react';
import { connect } from 'umi'
import { Upload, Modal, Button, Tag, Card, Space } from 'antd';
import { SortableContainer, SortableElement, sortableHandle } from 'react-sortable-hoc';
import DragAndDropHOC from './components/DraggableView';
import arrayMove from 'array-move';
import PromoterGroup from '@/components/SearchCondition/promoterGroup';
import { PlusOutlined, CloseCircleOutlined } from '@ant-design/icons';
import './index.less'
const DragHandle = sortableHandle(({ onDelete, value, setShowSetting, dispatch, reload, goodsId }) => {
  const { posterType, showFlag } = value
  const showShareImg = (value) => {
    const { showFlag, id, posterId } = value
    dispatch({
      type: showFlag === '1' ? 'promoter/fakeSetUnShow' : 'promoter/fakeSetShow',
      payload: {
        id: id ? id : '',
        posterId
      },
      callback: () => {
        reload()
      }
    })
  }
  if (posterType !== 'system') {
    return <>
      <CloseCircleOutlined onClick={(e) => {
        e.stopPropagation();
        onDelete(value);
      }}
        onMouseDown={(e) => {
          e.stopPropagation();
        }}
        style={{ position: 'absolute', top: 0, color: '#ffffff', right: 0, userSelect: 'none', zIndex: 1020 }}></CloseCircleOutlined>
      <div onClick={() => {
        const { groupIds } = value
        setShowSetting({
          show: true,
          detail: {
            ...value,
            groupIds: groupIds.length ? groupIds.split(',').map(val => {
              return Number(val)
            }) : []
          }
        })
      }} style={{
        background: '#000',
        bottom: 0,
        color: '#fff',
        cursor: 'pointer',
        fontSize: '12px',
        left: 0,
        opacity: 0.6,
        position: 'absolute',
        textAlign: 'center',
        width: '100%',
        zIndex: 1010
      }}>编辑</div>
    </>
  }
  else {
    return <>
      <div onClick={() => {
        showShareImg(value)
      }} style={{
        background: '#000',
        bottom: 0,
        color: '#fff',
        cursor: 'pointer',
        fontSize: '12px',
        left: 0,
        opacity: 0.6,
        position: 'absolute',
        textAlign: 'center',
        width: '100%',
        zIndex: 1010,
        border: 'none !important'
      }}>
        {showFlag === '1' ? '隐藏' : '显示'}</div>
      {showFlag === '0' && <div style={{
        position: 'absolute',
        left: 0,
        top: 0,
        bottom: 0,
        right: 0,
        background: 'rgba(0, 0, 0, 0.4)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#Ffffff'
      }}>图片已隐藏</div>}
      <Tag color='success' className='system_info'>系统推荐</Tag>
    </>

  }

})
// 可排序的单个元素
const SortableItem = SortableElement(({ value, onDelete, setShowSetting, dispatch, reload, goodsId }) => (
  <div className='ShareImgCollect_box' style={{ margin: '8px', zIndex: 888, position: 'relative', }}>
    <img src={value.bgImage} alt={value.name} style={{
      height: '200px',
      verticalAlign: 'bottom',
      width: '120px'
    }} />
    <DragHandle goodsId={goodsId} setShowSetting={setShowSetting} dispatch={dispatch} reload={reload} onDelete={onDelete} value={value}></DragHandle>
  </div>

));

// 可排序的容器
const SortableList = SortableContainer(({ items, onDelete, setShowSetting, dispatch, reload, goodsId }) => {
  return (
    <div style={{ display: 'flex', position: 'relative', flexWrap: 'wrap', alignItems: 'center' }}>
      {items.map((value, index) => {
        const { posterType, showFlag } = value
        return <SortableItem setShowSetting={setShowSetting} dispatch={dispatch} reload={reload} goodsId={goodsId} onDelete={onDelete} key={`item-${index}`} index={index} value={value} />
      })}
      <div style={{ marginTop: '8px' }} onClick={() => setShowSetting({ show: true })} className='setdetault_img'>
        <PlusOutlined></PlusOutlined>
      </div>
    </div>
  );
});

const SortableGallery = (props) => {
  const { dispatch, useFor, promoterType, title } = props
  const [fileList, setFileList] = useState([]);
  const [showSetting, setShowSetting] = useState(false)
  const [params, setParams] = useState({})
  const handleDelete = (item) => {
    const { id, posterId } = item
    Modal.confirm({
      title: '删除',
      content: '海报删除后不可恢复，确认删除吗？',
      okText: '删除',
      onOk() {
        dispatch({
          type: 'promoter/fakeRemovePoster',
          payload: {
            id,
            posterId
          },
          callback: (e) => {
            reload()
          },
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    })

  };
  const onSortEnd = ({ oldIndex, newIndex }) => {
    if (oldIndex !== newIndex) {
      dispatch({
        type: 'promoter/fakeSortPoster',
        payload: {
          sortPosterList: arrayMove(fileList, oldIndex, newIndex).map((item, index) => {
            return {
              id: item.id ? item.id : id,
              posterId: item.posterId,
              sortValue: index,
            }
          })
        },
        callback: (e) => {
          reload()
        }
      })
      setFileList(arrayMove(fileList, oldIndex, newIndex));
    }
  };
  useEffect(() => {
    reload()
  }, [params])
  const reload = () => {
    dispatch({
      type: 'promoter/fetchPromoterPoster',
      payload: {
        useFor,
        promoterType,
        ...params
      },
      callback: (e) => {
        setFileList(e)
      },
    });
  }
  return (
    <React.Fragment>
      <Card bordered={false} title={<Space>
        <div>{title}</div>
        <PromoterGroup hasAll={true} value={params.groupId} onChange={(e) => {
          setParams({
            groupId: e
          })
        }} style={{ width: 180 }}></PromoterGroup>
      </Space>}>
        <div style={{}}>
          <Space>
            <SortableList distance={1} reload={reload} dispatch={dispatch} setShowSetting={setShowSetting} onDelete={handleDelete} items={fileList} onSortEnd={onSortEnd} axis="xy" />

          </Space>
        </div>
      </Card>
      <DragAndDropHOC useFor={useFor} reload={reload} dispatch={dispatch} visible={showSetting} onClose={() => setShowSetting({ show: false })}></DragAndDropHOC>
    </React.Fragment >

  );
};
export default connect(({ behaviorEecord, loading }) => ({
  loading: loading.models.behaviorEecord,
}))(SortableGallery);


